package com.example.netty.netty.TCPExample;

import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.util.ReferenceCountUtil;

import java.net.InetSocketAddress;

/**
 * @Author: 江涛
 * @CreateTime: 2022-09-27  10:04
 * @Description:
 */
public class NettyServerOutBandHandler extends ChannelOutboundHandlerAdapter {
    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        ChannelFuture bind = ctx.bind(new InetSocketAddress(6666));
        while (!bind.isDone()) {
            Thread.sleep(100);
        }
        // TODO: 2022/9/27 ?
        System.out.println("已成功将端口改为6666，看是否能成功发送消息，端口号："+ctx.channel().localAddress());

        System.out.println("将数据写入channel");
//        System.out.println("释放消息，则无法发送到客户端");
//        ReferenceCountUtil.release(msg);
//        promise.setSuccess();
        super.write(ctx, msg, promise);
    }

    @Override
    public void flush(ChannelHandlerContext ctx) throws Exception {
        System.out.println("将数据推送到远程客户端");
        //一定执行父类方法，不要客户端无法接收到消息
        super.flush(ctx);
    }


}
